@using System.Text.Json
@model VotingSystem.ViewModels.VoteViewModel

@{
    ViewData["Title"] = "投票结果";
}

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <h2 class="card-title mb-2">@Model.Title - 投票结果</h2>
                    <p class="text-muted mb-3">@Model.Description</p>
                    <div class="mb-2 small text-secondary">
                        <span class="me-3"><i class="fas fa-clock"></i> 创建：@Model.CreateTime.ToString("yyyy-MM-dd HH:mm")</span>
                        <span class="me-3"><i class="fas fa-hourglass-end"></i> 截止：@Model.EndTime.ToString("yyyy-MM-dd HH:mm")</span>
                        <span class="me-3"><i class="fas fa-users"></i> 总票数：@Model.TotalVotes</span>
                        <span class="me-3"><i class="fas fa-user-secret"></i> @(Model.IsPublic ? "公开" : "私密")</span>
                        <span class="me-3"><i class="fas fa-user"></i> @(Model.IsAnonymous ? "匿名" : "实名")</span>
                        <span class="me-3"><i class="fas fa-info-circle"></i> 状态：<span class="badge @(Model.IsActive ? "bg-success" : "bg-secondary")">@(Model.IsActive ? "进行中" : "已结束")</span></span>
                    </div>
                </div>
            </div>

            @if (Model.CanViewResults)
            {
                <div class="card mb-4">
                    <div class="card-header">投票结果</div>
                    <div class="card-body">
                        @if (Model.Type == VotingSystem.Models.VoteType.Rating)
                        {
                            <h5 class="mb-3">评分结果</h5>
                            
                            <!-- 添加评分结果图表 -->
                            <div class="row mb-4">
                                <div class="col-md-8">
                                    <canvas id="ratingChart" class="mb-3"></canvas>
                                </div>
                                <div class="col-md-4">
                                    <canvas id="ratingDistributionChart" class="mb-3"></canvas>
                                </div>
                            </div>
                            
                            @foreach (var option in Model.Options)
                            {
                                <div class="mb-4">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <h6>@option.Title</h6>
                                        <span class="badge bg-info">@option.Votes 人评分</span>
                                    </div>
                                    @if (!string.IsNullOrEmpty(option.Description))
                                    {
                                        <p class="text-muted small mb-2">@option.Description</p>
                                    }
                                    <div class="d-flex justify-content-between mb-1">
                                        <span>平均分: @option.AverageRating.ToString("0.00") / @option.MaxRating</span>
                                        @{
                                            var ratingPercent = option.AverageRating > 0 && option.MaxRating.HasValue ? 
                                                (option.AverageRating * 100 / option.MaxRating.Value) : 0;
                                        }
                                        <span>@ratingPercent.ToString("0.00")%</span>
                                    </div>
                                    <div class="progress" style="height: 20px;">
                                        <div class="progress-bar bg-warning" role="progressbar" 
                                             style="width: @(ratingPercent)%">
                                        </div>
                                    </div>
                                </div>
                            }
                        }
                        else
                        {
                            <canvas id="voteChart" class="mb-4"></canvas>
                            @foreach (var option in Model.Options)
                            {
                                var percent = Model.TotalVotes > 0 ? (option.Votes * 100.0 / Model.TotalVotes) : 0;
                                <div class="mb-3">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <span>@option.Title</span>
                                        <span class="small text-muted">@option.Votes 票 (@percent.ToString("0.00")%)</span>
                                    </div>
                                    <div class="progress" style="height: 20px;">
                                        <div class="progress-bar bg-info" role="progressbar" style="width: @percent%">
                                            @percent.ToString("0.00")%
                                        </div>
                                    </div>
                                </div>
                            }
                        }
                        <button class="btn btn-outline-success btn-sm mt-3" onclick="exportCSV()">
                            <i class="fas fa-file-csv"></i> 导出结果
                        </button>
                    </div>
                </div>
            }

            <!-- 参与者列表，仅实名投票显示 -->
            @if (!Model.IsAnonymous && Model.Participants?.Any() == true)
            {
                // 对参与者进行分组，确保每个用户只显示一次
                var uniqueParticipants = Model.Participants
                    .GroupBy(p => p.Name)
                    .Select(g => g.OrderByDescending(p => p.VoteTime).First())
                    .ToList();
                
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>参与者列表（@uniqueParticipants.Count）</span>
                        <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#participantsList">
                            <i class="fas fa-chevron-down"></i>
                        </button>
                    </div>
                    <div class="collapse show" id="participantsList">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>参与者</th>
                                            <th>投票时间</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach (var participant in uniqueParticipants)
                                        {
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-user-circle me-2 text-primary"></i>
                                                        <span>@participant.Name</span>
                                                    </div>
                                                </td>
                                                <td>@participant.VoteTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            }

            <div class="d-flex gap-2 mb-4">
                <button onclick="history.back()" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left"></i> 返回上一页
                </button>
            </div>
        </div>
    </div>
</div>

@section Styles {
    <style>
        .progress-bar {
            font-size: 1rem;
        }
    </style>
}

@section Scripts {
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        @if (Model.Type == VotingSystem.Models.VoteType.Rating)
        {
            <text>
            // 评分类型的图表渲染
            const ratingLabels = @Html.Raw(JsonSerializer.Serialize(Model.Options.Select(o => o.Title)));
            const ratingData = @Html.Raw(JsonSerializer.Serialize(Model.Options.Select(o => o.AverageRating)));
            const votesData = @Html.Raw(JsonSerializer.Serialize(Model.Options.Select(o => o.Votes)));
            
            // 柱状图 - 显示每个选项的平均评分
            const ratingCtx = document.getElementById('ratingChart');
            if (ratingCtx) {
                new Chart(ratingCtx, {
                    type: 'bar',
                    data: {
                        labels: ratingLabels,
                        datasets: [{
                            label: '平均评分',
                            data: ratingData,
                            backgroundColor: 'rgba(255, 193, 7, 0.5)',
                            borderColor: 'rgba(255, 193, 7, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { display: true },
                            title: {
                                display: true,
                                text: '各选项平均评分对比'
                            }
                        },
                        scales: {
                            y: { 
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '平均分'
                                }
                            }
                        }
                    }
                });
            }
            
            // 饼图 - 显示评分分布
            const distributionCtx = document.getElementById('ratingDistributionChart');
            if (distributionCtx) {
                new Chart(distributionCtx, {
                    type: 'pie',
                    data: {
                        labels: ratingLabels,
                        datasets: [{
                            data: votesData,
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.7)',
                                'rgba(54, 162, 235, 0.7)',
                                'rgba(255, 206, 86, 0.7)',
                                'rgba(75, 192, 192, 0.7)',
                                'rgba(153, 102, 255, 0.7)',
                                'rgba(255, 159, 64, 0.7)',
                                'rgba(199, 199, 199, 0.7)',
                                'rgba(83, 102, 255, 0.7)',
                                'rgba(40, 159, 64, 0.7)',
                                'rgba(210, 199, 199, 0.7)',
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { 
                                display: true,
                                position: 'right'
                            },
                            title: {
                                display: true,
                                text: '评分分布'
                            }
                        }
                    }
                });
            }
            </text>
        }
        else
        {
            <text>
            // Chart.js 渲染
            const labels = @Html.Raw(JsonSerializer.Serialize(Model.Options.Select(o => o.Title)));
            const data = @Html.Raw(JsonSerializer.Serialize(Model.Options.Select(o => o.Votes)));
            const ctx = document.getElementById('voteChart');
            if (ctx) {
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: '票数',
                            data: data,
                            backgroundColor: 'rgba(54, 162, 235, 0.5)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { display: false }
                        },
                        scales: {
                            y: { beginAtZero: true, precision:0 }
                        }
                    }
                });
            }
            </text>
        }

        // 导出CSV
        function exportCSV() {
            let csv = '';
            @if (Model.Type == VotingSystem.Models.VoteType.Rating)
            {
                <text>
                csv = '选项,评分人数,平均分\n';
                @foreach (var o in Model.Options)
                {
                    <text>csv += '@o.Title,@o.Votes,@o.AverageRating.ToString("0.00")\n';</text>
                }
                </text>
            }
            else
            {
                <text>
                csv = '选项,票数\n';
                @foreach (var o in Model.Options)
                {
                    <text>csv += '@o.Title,@o.Votes\n';</text>
                }
                </text>
            }
            let blob = new Blob([csv], {type: 'text/csv'});
            let link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = '投票结果.csv';
            link.click();
        }
    </script>
} 